<?php

require_once('adept/Exception.php');

final class Adept 
{
    
    static function addIncludePath($path)
    {
    	set_include_path(get_include_path() . PATH_SEPARATOR . $path);
    }
	
	static function loadClass($className) 
	{
		if (class_exists($className, false)) {
			return ;
		}
		
		$parts = explode("_", $className);
		if (count($parts) == 1) {
			self::loadFile($className . '.php', explode(PATH_SEPARATOR, get_include_path()));
		} else {
			$path = "";
			for($i = 0; $i < count($parts) - 1; $i++) {
				$path .= $parts[$i] . DIRECTORY_SEPARATOR;
			}
			self::loadFile($path . end($parts) . '.php', explode(PATH_SEPARATOR, get_include_path()));
		}
		if (!class_exists($className, false)) {
			throw new Adept_Exception("Cannot autoload class {$className}");
		}
	}	
	
	static function loadInteface($className) 
	{
		if (class_exists($className, false)) {
			return ;
		}
		$parts = explode("_", $className);
		if (count($parts) == 1) {
			self::loadFile($className . '.php', explode(PATH_SEPARATOR, get_include_path()));
		} else {
			$path = "";
			for($i = 0; $i < count($parts) - 1; $i++) {
				$path .= $parts[$i] . DIRECTORY_SEPARATOR;
			}
			self::loadFile($path . end($parts) . '.php', explode(PATH_SEPARATOR, get_include_path()));
		}
		if (!class_exists($className, false)) {
			throw new Adept_Exception("Cannot autoload interface {$className}");
		}
	}		
	
	static function loadFile($fileName, $dirs = array(), $once = true, $require = true) 
	{
		$fullPath = $fileName;
		$isFound = file_exists($fileName);
		
		if (count($dirs) > 0 && !$isFound) {
			if ($fileName[0] != '/' || $fileName[0] != '\\') {
				$fileName = DIRECTORY_SEPARATOR . $fileName;
			}
			
			foreach ($dirs as $dir) {
				
				if (file_exists($dir . $fileName)) {
					$fullPath = $dir . $fileName;
					$isFound = true;
					break;
				}
			}
		}
		
		if (!$isFound) {
			throw new Adept_Exception("File '{$fileName}' not found", 0, array('dirs' => $dirs));
		}
		
		if ($once) {
		    if ($require) {
			    require_once($fullPath);
		    } else {
		        include_once($fullPath);
		    }
		  
		} else {
		    if ($require) {
			    require($fullPath);
		    } else {
		        include($filePath);
		    }
		}
	}		
	
	static function init() 
	{
		$adeptDir = dirname(__FILE__);
		define('ADEPT_DIR', $adeptDir);
		set_include_path(get_include_path() . PATH_SEPARATOR . $adeptDir);
	}
	
}

// Autoload magic manipulations
function __autoload($class) 
{
    Adept::loadClass($class);
}

Adept::init();
